<template>
	<view class="the-page">
		<uni-forms :model="userForm" ref="form1" :label-width="90">
			<uni-forms-item label="Id"><uni-easyinput type="text" v-model="userForm.id" disabled /></uni-forms-item>
			<uni-forms-item label="用户"><uni-easyinput type="text" v-model="userForm.name" disabled /></uni-forms-item>
			<uni-forms-item label="原来密码" prop="password" required>
				<uni-easyinput type="password" v-model="userForm.password" placeholder="请输入原密码" />
			</uni-forms-item>
			<uni-forms-item label="新的密码" prop="password2" required>
				<uni-easyinput type="password" v-model="userForm.password2" placeholder="请输入新密码" />
			</uni-forms-item>
			<uni-forms-item label="确认密码" prop="password22" required>
				<uni-easyinput type="password" v-model="userForm.password22" placeholder="请输入新密码" />
			</uni-forms-item>
		</uni-forms>
		<button type="primary" @click="onSubmit">提交</button>

	</view>
</template>

<script>
	import * as userAPI from '@/api/user.js';
	import { getStorageUser } from '@/utils/storage.js';
	export default {
		data() {
			return {
				userForm: {
					id: null,
					name: '',
					password: '',
					password2: '', //新的密码
					password22: '' //确认密码
				},

				//规则:字母数字
				rules: {
					password: {
						type: 'string',
						required: true,
						pattern: /^[a-z0-9]{3,12}$/i,
						message: '3-12字符',
						trigger: ['blur', 'change']
					},
					password2: {
						type: 'string',
						required: true,
						pattern: /^[a-z0-9]{3,12}$/i,
						message: '3-12字符',
						trigger: ['blur', 'change']
					},
					password22: {
						type: 'string',
						required: true,
						pattern: /^[a-z0-9]{3,12}$/i,
						message: '3-12字符',
						trigger: ['blur', 'change']
					}
				}
			};
		},
		onLoad() {
			let user = getStorageUser();
			this.userForm.id = user.id;
			this.userForm.name = user.name;
		},
		onReady() {
			// 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
			this.$refs.form1.setRules(this.rules);
		},
		methods: {
			//处理提交保存
			onSubmit() {
				if (this.userForm.password2 != this.userForm.password22) {
					uni.showToast({
						title: '确认密码两次输入不一致！',
						icon: 'error'
					});
					return;
				}

				this.$refs.form1
					.validate()
					.then(valid => {
						if (valid) {
							//注意传递过去的参数的属性名要一致
							let params = {};
							params.id = this.userForm.id;
							params.passwordOld = this.userForm.password;
							params.passwordNew = this.userForm.password2;

							userAPI.updatePwd(params).then(() => {
								uni.showToast({
									title: '密码更改成功！',
									icon: 'success'
								});
								setTimeout(() => {
									uni.navigateBack({
										delta: 1, //	url: '/pages/user/user'			
									});
								}, 1000);
							});
						}
					})
					.catch(() => {
						uni.showToast({
							title: '校验失败！',
							icon: 'error'
						});
					});
			},

		}
	};
</script>

<style lang="less" scoped>
	.the-page {
		padding: 20px;
	}

	uni-button {
		margin: 10px 0;
	}
</style>